#!/bin/bash
set -e

BACKUP_NAME="backup"
BACKUP_DATE=`date +%Y%m%d_%H%M%S`


function help()
{
    echo -e "usage:"
    echo -e "./tf_save.sh --save_disk /dev/sdb --save_GB 22"
    echo -e "./tf_save.sh -d /dev/sdb -s 22"

}


while [ -n "$1" ]
do
    case "$1" in
        --save_disk|-d) 
            SAVE_DISK=$2
            shift
            ;;
        --save_GB|-s) 
            SAVE_GB=$2
            shift
            ;;
        --help|-h) 
            help
            exit 1
            ;;
        *) echo "[-] Parameters of illegal !!!"
            help
            exit 1
            ;;
    esac
    shift
done


echo "SAVE_DISK=${SAVE_DISK}"
echo "SAVE_GB=${SAVE_GB}"


if [[ -z ${SAVE_DISK}  || -z ${SAVE_GB} ]]
then
    echo -e "\e[31mParameters invalid !!!\e[0m"
    exit 1
fi
echo -e "\e[36mParameters OK !!!\e[0m"




sudo watch -n 10 killall -USR1 dd > /dev/null 2>&1 &
sudo dd if=${SAVE_DISK} bs=8M count=$[SAVE_GB*128] of=${BACKUP_NAME}_${BACKUP_DATE}.img

sudo killall watch
sudo chown ${USER}:${USER} ${BACKUP_NAME}_${BACKUP_DATE}.img

echo "if need compress img file"
echo "pigz *.img" 